<script lang="ts" setup>
import { transform } from 'lodash';
import { reactive } from 'vue';
const drag = reactive({
  dragging: false,
  top: 0,
  left: 0,
  initialTop: 0,
  initialLeft: 0,
  mouseX: 0,
  mouseY: 0,
  scale: 1
});

const startDrag = (event) => {
  // 鼠标按下时开始拖拽
  event.preventDefault();
  drag.dragging = true;
  drag.mouseX = event.clientX;
  drag.mouseY = event.clientY;
  drag.initialTop = drag.top;
  drag.initialLeft = drag.left;

  // 监听全局的鼠标移动和松开事件
  document.addEventListener('mousemove', dragHandle);
  document.addEventListener('mouseup', stopDrag);
};
const dragHandle = (event) => {
  // 拖拽过程中更新元素位置
  if (drag.dragging) {
    const deltaX = event.clientX - drag.mouseX;
    const deltaY = event.clientY - drag.mouseY;
    drag.left = drag.initialLeft + deltaX;
    drag.top = drag.initialTop + deltaY;
  }
};
const stopDrag = (event) => {
  // 停止拖拽
  drag.dragging = false;
  console.log(event);

  if (drag.left < 0 || drag.top < 0) {
    drag.scale = 0.6;
  }
  // 移除全局的事件监听器
  document.removeEventListener('mousemove', dragHandle);
  document.removeEventListener('mouseup', stopDrag);
};
</script>

<template>
  <div class="h-full w-full overflow-hidden">
    <div class="h-full w-full" :style="{ transform: `scale(${drag.scale})` }">
      <div
        class="w-36 h-36 bg-black drag-dom"
        :style="{ transform: `translate(${drag.left}px, ${drag.top}px) ` }"
        @mousedown="startDrag"
      ></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.drag-dom {
  width: 300px;
  height: 200px;
  background-color: #000;
  cursor: move;
}
</style>
